<template>
  <div v-if="showStatus" :class="['api-status', status]">
    <el-icon v-if="status === 'connected'"><Check /></el-icon>
    <el-icon v-else-if="status === 'disconnected'"><Close /></el-icon>
    <el-icon v-else><Loading /></el-icon>
    
    <span>{{ statusMessage }}</span>
    
    <el-button v-if="status === 'disconnected'" 
               size="small" 
               @click="checkConnection" 
               :loading="checking">
      重试
    </el-button>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { Check, Close, Loading } from '@element-plus/icons-vue';
import { checkApiConnection } from '@/utils/network';

const props = defineProps({
  showStatus: {
    type: Boolean,
    default: true
  }
});

const status = ref('checking'); // 'checking', 'connected', 'disconnected'
const checking = ref(false);

const statusMessage = computed(() => {
  switch (status.value) {
    case 'connected':
      // return '服务器连接正常';
    case 'disconnected':
      return '无法连接到服务器';
    default:
      return '检查服务器连接...';
  }
});

const checkConnection = async () => {
  status.value = 'checking';
  checking.value = true;
  
  try {
    const apiUrl = import.meta.env.VITE_API_BASE_URL;
    const isConnected = await checkApiConnection(apiUrl);
    
    status.value = isConnected ? 'connected' : 'disconnected';
  } catch (error) {
    console.error('检查API连接失败:', error);
    status.value = 'disconnected';
  } finally {
    checking.value = false;
    
    // 如果连接成功，5秒后隐藏状态
    if (status.value === 'connected') {
      setTimeout(() => {
        if (status.value === 'connected') {
          status.value = 'hidden';
        }
      }, 5000);
    }
  }
};

onMounted(() => {
  checkConnection();
});
</script>

<style scoped>
.api-status {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 10px 15px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 9999;
  font-size: 14px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.api-status.connected {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #e1f3d8;
}

.api-status.disconnected {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
}

.api-status.checking {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #e9e9eb;
}

.api-status .el-icon {
  font-size: 16px;
}
</style> 